package com.jike.task.week02;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.security.KeyStore;
import java.util.concurrent.Semaphore;

/**
 * @author Administrator
 */
public class HttpClientUtil {
    private static final OkHttpClient httpClient = OkHttpClientEnum.CLIENT.getClientInstance();

    private static Semaphore semaphore = new Semaphore(0);


    public static Semaphore getSemaphoreInstance(){
        return semaphore;
    }


    public static String httpClientGet(String url) throws Exception {
        final StringBuilder buffer = new StringBuilder("");
        //获取信任证书库
        KeyStore trustStore = null;
        //OkHttpClient client  = httpClient;
        final Request request = new Request.Builder()
                .url(url)
                .get().build();
        final Call call     = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                getSemaphoreInstance().release();//释放
                try {
                    throw e;
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException
            {
                String res = response.body().string();
                buffer.append(res);
                getSemaphoreInstance().release();//释放
            }
        });
        try {
            getSemaphoreInstance().acquire();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        return buffer.toString();
    }
}
